package net.hvacapp.cmvrfforandroid.ui.project;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.method.DigitsKeyListener;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.mirror.android.common.util.StringUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.manager.ProjectManager;
import net.hvacapp.cmvrfforandroid.ui.BaseActivity;
import net.hvacapp.cmvrfforandroid.ui.EventBus.ProjectListRefreshEvent;
import net.hvacapp.cmvrfforandroid.ui.MainTabBarActivity;
import net.hvacapp.cmvrfforandroid.ui.project.model.EquiptPriceData;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetEquiptPriceDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetProjectInfoDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetProjectTempleteDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.ProjectInfoData;
import net.hvacapp.cmvrfforandroid.ui.project.model.ProjectTempleteData;
import net.hvacapp.cmvrfforandroid.ui.project.view.TwoLinesCellView;
import net.hvacapp.cmvrfforandroid.ui.selections.model.AreaData;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;
import net.hvacapp.cmvrfforandroid.utils.NumberUtil;
import net.hvacapp.cmvrfforandroid.widget.IOSAlertView;
import net.hvacapp.cmvrfforandroid.widget.ProjectActionView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

@EActivity(R.layout.activity_project_status_modify)
public class ProjectStatusModifyActivity extends BaseActivity {

    @ViewById(R.id.tv_left)
    TextView mLeftTv;
    @ViewById(R.id.tv_right)
    TextView mRightTv;

    @ViewById(R.id.project_status)
    TwoLinesCellView mProjectStatusCv;
    @ViewById(R.id.project_price)
    TwoLinesCellView mProjectPriceCv;
    @ViewById(R.id.transfer_price)
    TwoLinesCellView mTransferPriceCv;


    private Dialog mProgressDlg;
    private int mCurrentPhase;




    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initViews();
        initEvent();
    }

    /***
     * 初始化视图
     */
    private void initViews() {

        mProjectStatusCv.setTitleString("项目进度");
        mProjectStatusCv.setItemSelected(true);
        mProjectPriceCv.setTitleString("原价(元)");
        mProjectPriceCv.setItemSelected(false);
        mTransferPriceCv.setTitleString("成交价（元）");
        mTransferPriceCv.setItemSelected(true);

    }

    private void setViewData() {
        ProjectInfoData data = ProjectManager.getInstance().getProjectData();
        mProjectStatusCv.setDescString(data.getPhaseString());
        mProjectPriceCv.setDescString(NumberUtil.formateMoney(data.getTotalPrice()));
        mTransferPriceCv.setDescString(NumberUtil.formateMoney(data.getTransPrice()));
    }

    private void editPrice(final int type, String title) {
        final EditText priceEt = new EditText(this);
        priceEt.setKeyListener(new DigitsKeyListener(false,true));
        new AlertDialog.Builder(this).setTitle(title)
                .setView(priceEt)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            double price = Double.valueOf(priceEt.getText().toString());
                            if (price > 0) {
                                //修改报价
                                if (type == 1) {
                                    mCurrentPhase = ProjectInfoData.PROJECT_PHASE_INPROGRESS;
                                }
                                else if (type == 2) {
                                    ProjectManager.getInstance().getProjectData().setTaxRate(price/100);
                                }
                                else {
                                    ProjectManager.getInstance().getProjectData().setTransPrice(price);
                                }
                                modifyProjectInfo(ProjectManager.getInstance().getProjectData());
                            }
                        }
                        catch (Exception e) {

                        }
                    }
                })

                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 初始化
     */
    @Override
    public void initBoot() {
        setupToolbar(0, "项目进度", null);

        setButton1Info("删除", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IOSAlertView.showAlertView(ProjectStatusModifyActivity.this, "提示", "确定删除项目？", "确定", new IOSAlertView.OnAlertViewClickListener() {
                    @Override
                    public void OnAlertViewClick(int position) {
                        if (position == 0) {
                            deleteProject(ProjectManager.getInstance().getProjectData().getGuidId());
                        }
                    }
                }, "取消");
            }
        });

    }


    /**
     * 初始化数据
     */
    @Override
    public void initData(Intent intent) {
        loadProject(ProjectManager.getInstance().getProjectData().getGuidId());
    }



    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    private void initEvent() {
        mLeftTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //修改项目进度
                if (mCurrentPhase == ProjectManager.getInstance().getProjectData().getPhase()) {
                    showMessage("请先修改项目进度");
                    return;
                }

                final int originPhase = ProjectManager.getInstance().getProjectData().getPhase();
                mProgressDlg = createProgressBarDialog(ProjectStatusModifyActivity.this, "修改项目进度中...");
                mProgressDlg.show();

                ProjectManager.getInstance().getProjectData().setPhase(mCurrentPhase);
                Map<String, Object> param = new HashMap<>();
                param.put("prjInfo", ProjectManager.getInstance().getProjectData());

                BasicHttpClient.httpPostAsync(HttpConstant.HTTP_POST_PROJECT_INFO, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProjectInfoDataResp>() {
                    @Override
                    public void onSuccess(GetProjectInfoDataResp obj) {
                        //需要重新拉取所有的系统数据
                        mProgressDlg.dismiss();
                        IOSAlertView.showAlertView(ProjectStatusModifyActivity.this, "提示", "项目进度修改成功！", "确定", new IOSAlertView.OnAlertViewClickListener() {
                            @Override
                            public void OnAlertViewClick(int position) {
                                EventBus.getDefault().post(new ProjectListRefreshEvent());
                                finish();
                            }
                        });
                    }

                    @Override
                    public void onFailure(String response) {
                        mProgressDlg.dismiss();
                        ProjectManager.getInstance().getProjectData().setPhase(originPhase);
                        showMessage("项目进度修改失败！");
                    }
                });
            }
        });

        mRightTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下一步
                ProjectManager.getInstance().setStatus(ProjectManager.PROJECT_STATUS_MODIFY);
                startActivity(new Intent(ProjectStatusModifyActivity.this, AnnotationUtil.get(ProjectStep1Activity.class)));
            }
        });

        mProjectStatusCv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //选择状态
                String[] items = ProjectStatusModifyActivity.this.getResources().getStringArray(
                        R.array.phaseArray);
                new android.app.AlertDialog.Builder(ProjectStatusModifyActivity.this)
                        .setTitle("选择项目状态")
                        .setItems(items, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog,
                                                int which) {
                                switch (which) {
                                    case 0:
                                        mCurrentPhase = ProjectInfoData.PROJECT_PHASE_INPROGRESS;
                                        mProjectStatusCv.setDescString("进行中");
                                        break;
                                    case 1:
                                        mCurrentPhase = ProjectInfoData.PROJECT_PHASE_NOTDEAL;
                                        mProjectStatusCv.setDescString("未成交");
                                        break;
                                    case 2:
                                        mCurrentPhase = ProjectInfoData.PROJECT_PHASE_DEAL;
                                        mProjectStatusCv.setDescString("已成交");
                                        break;
                                    default:
                                        break;
                                }
                                //修改项目信息
//                                modifyProjectInfo(ProjectManager.getInstance().getProjectData());
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .show();

            }
        });

        mTransferPriceCv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //编辑价格
                editPrice(3, "成交价格");
            }
        });

    }

    private void loadProject(String guid) {
        Map<String, Object> param = new HashMap<>();
        param.put("pid", guid);
        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_BY_GUID, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProjectInfoDataResp>() {
            @Override
            public void onSuccess(GetProjectInfoDataResp obj) {
                // 成功
                ProjectManager.getInstance().setProjectData(obj.getGetProjectResult());
                //设置视图
                mCurrentPhase = obj.getGetProjectResult().getPhase();
                setViewData();
            }

            @Override
            public void onFailure(String response) {

            }
        });
    }

    private void modifyProjectInfo(ProjectInfoData data) {
        Map<String, Object> param = new HashMap<>();
        param.put("prjInfo", data);

        BasicHttpClient.httpPostAsync(HttpConstant.HTTP_POST_PROJECT_INFO, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProjectInfoDataResp>() {
            @Override
            public void onSuccess(GetProjectInfoDataResp obj) {
                //需要重新拉取所有的系统数据
                ProjectManager.getInstance().setProjectData(obj.getModifyResult());
                setViewData();
            }

            @Override
            public void onFailure(String response) {
                showMessage("报价修改失败！");
            }
        });

    }

    private void deleteProject(String guidId) {
        Map<String, Object> param = new HashMap<>();
        param.put("pid", guidId);

        mProgressDlg = createProgressBarDialog(ProjectStatusModifyActivity.this, "项目删除中...");
        mProgressDlg.show();

        BasicHttpClient.httpDeleteAsync(HttpConstant.HTTP_DELETE_PROJECT, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProjectInfoDataResp>() {
            @Override
            public void onSuccess(GetProjectInfoDataResp obj) {
                mProgressDlg.dismiss();
                IOSAlertView.showAlertView(ProjectStatusModifyActivity.this, "提示", "项目删除成功！", "确定", new IOSAlertView.OnAlertViewClickListener() {
                    @Override
                    public void OnAlertViewClick(int position) {
                        EventBus.getDefault().post(new ProjectListRefreshEvent());
                        finish();
                    }
                });
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                showMessage("项目删除失败！");
            }
        });
    }



}
